package com.wontube.smr.bo.sites.fs;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.wontube.client.extension.utils.net.URLUtils;
import com.wontube.smr.bo.sites.fs.mp3skull.Mp3SkullHtmlParser;
import com.wontube.smr.client.model.vo.AudioFile;
import com.wontube.smr.client.model.vo.AudioFiles;
import com.wontube.smr.dao.bo.KeywordFilterDao;

/**
 * @author yuechao
 *
 */
public final class Mp3SearchBO {
	private Mp3SearchBO() {
	}
	
	private static String apiUrl = "http://search.4shared.com/network/searchXml.jsp?searchCategory=music/audio&searchExtention=mp3&sortType=5&sortOrder=1&searchmode=3";

	/**
	 * 查询音乐，如果是英文，先从mp3skull抓取，如果无记录，再从4shared.com查询
	 * 如果包含其他语言，直接从4shared.com查询
	 * 
	 * @param query
	 * @param pageIndex 从1开始
	 * @return
	 * @throws Exception
	 */
	public static final AudioFiles search(String query, int pageIndex) throws Exception {
		AudioFiles files = Mp3SkullHtmlParser.parse(query, pageIndex);
		if (files.getFiles().size() > 0) {
			return files;
		}
		
		if (!files.isCopyright()) {
			return files;
		}
		
		if (!KeywordFilterDao.isKeywordCopyright(KeywordFilterDao.keyTypeMusic, query)) {
			files.setCopyright(false);
			return files;
		}
		
		files = new AudioFiles();
		String q = URLUtils.encodeURIComponent(query);
		int start = (pageIndex - 1) * 10; // 先假定一页10项
		String url = apiUrl + "&q=" + q + "&start=" + start;
		
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setConnectTimeout(20000);
		conn.setReadTimeout(20000);
		conn.setUseCaches(false);
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5");
		conn.connect();
		
		InputStream stream = conn.getInputStream();
		SearchParseService service = new SearchParseService();
		
		try {		
			files = service.getAudioFiles(stream);

			// 修正api错误
			AudioFiles temp = files;
			int count = temp.getStart() + temp.getFiles().size();
			while (count < files.getTotalCount() && files.getFiles().size() < files.getPageSize()) {
				start += files.getFiles().size();
				url = apiUrl + "&q=" + q + "&start=" + start;
				stream.close();
				conn.disconnect();
				
				uri = new URL(url);
				conn = (HttpURLConnection) uri.openConnection();
				conn.setConnectTimeout(20000);
				conn.setReadTimeout(20000);
				conn.setUseCaches(false);
				conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5");
				conn.connect();
				
				stream = conn.getInputStream();
				temp = service.getAudioFiles(stream);
				count += temp.getFiles().size();
				if (temp.getFiles().size() < 1) {
					// 修正
					files.setTotalCount(count);
					break;
				}
					
				// 需要丢弃多余的
				List<AudioFile> list = temp.getFiles();
				for (int i = 0; i < list.size() && files.getFiles().size() < files.getPageSize(); i++) {
					files.getFiles().add(list.get(i));
				}
			}
			files.setCookie(conn.getHeaderField("Set-Cookie"));
		} finally {
			stream.close();
			conn.disconnect();
		}
		
		return files;
	}
}
